<template>
    <v-container>
        <v-row>
            <v-col>
                <v-card>
                    <v-form class="pa-6">
                        <v-text-field v-model="name" append-icon="mdi-magnify" label="姓名" single-line hide-details
                            clearable></v-text-field>
                        <v-dialog ref="dialog" v-model="modal" :return-value.sync="dates" persistent width="290px">
                            <template v-slot:activator="{ on, attrs }">
                                <v-text-field v-model="date" label="时间" append-icon="mdi-magnify" readonly clearable
                                    @click:clear="onClearDate" v-bind="attrs" v-on="on"></v-text-field>
                            </template>
                            <v-date-picker :first-day-of-week="0" locale="zh-cn" v-model="dates" scrollable range>
                                <v-spacer></v-spacer>
                                <v-btn text color="primary" @click="modal = false; dates = []">
                                    取消
                                </v-btn>
                                <v-btn text color="primary" @click="$refs.dialog.save(dates)">
                                    确定
                                </v-btn>
                            </v-date-picker>
                        </v-dialog>
                        <v-btn :disabled="loading" class="mr-4" @click="getLog" color="primary">
                            查询
                        </v-btn>
                        <v-btn :disabled="loading" class="mr-4" @click="exportLog" color="primary">
                            导出
                        </v-btn>
                    </v-form>
                    <v-data-table :headers="headers" :items="logs" item-key="id" show-expand single-expand
                        :sort-by="['id']" sort-desc @item-expanded="onItemExpanded" :options.sync="options"
                        :server-items-length="logCount" :loading="loading">
                        <template v-slot:expanded-item="{ headers, item }">
                            <td :colspan="headers.length" class="pa-6">
                                <v-data-table :headers="headersDetail" group-by="dispense"
                                    :items="logDetails.filter(itemToFilter => itemToFilter.parentId == item.id)"
                                    group-desc tile hide-default-footer>

                                    <template v-slot:[`group.header`]="{ group }">
                                        <v-card v-if="group" class="d-flex pa-2" flat>
                                            借出
                                        </v-card>
                                        <v-card v-else class="d-flex pa-2" flat>
                                            归还
                                        </v-card>
                                    </template>

                                    <template v-slot:[`item.tool_type`]="{ item }">
                                        {{
                                            toolTypes.find(itemToFind => itemToFind.id == toolList.find(itemToFind =>
                                                itemToFind.id == item.tool).type).name
                                        }}
                                    </template>

                                    <template v-slot:[`item.tool`]="{ item }">
                                        {{ toolList.find(itemToFind => itemToFind.id == item.tool).name }}
                                    </template>

                                    <template v-slot:[`item.identifier`]="{ item }">
                                        {{ toolList.find(itemToFind => itemToFind.id == item.tool).identifier }}
                                    </template>

                                    <template v-slot:[`item.drawer`]="{ item }">
                                        {{
                                            drawerList.find(itemToFind => itemToFind.id == toolList.find(itemToFind =>
                                                itemToFind.id == item.tool).drawer).name
                                        }}
                                    </template>

                                    <template v-slot:no-data>
                                        没有数据！
                                    </template>
                                </v-data-table>
                            </td>
                        </template>
                        <template v-slot:[`item.actions`]="{ item }">
                            <v-icon small @click="deleteItem(item)">
                                mdi-delete
                            </v-icon>
                        </template>
                        <template v-slot:no-data>
                            没有数据！
                        </template>
                    </v-data-table>
                    <v-dialog v-model="dialogDelete" max-width="300px">
                        <v-card>
                            <v-card-title class="text-h6">确定要删除这条记录吗？</v-card-title>
                            <v-card-actions>
                                <v-spacer></v-spacer>
                                <v-btn color="blue darken-1" text @click="closeDelete">取消</v-btn>
                                <v-btn color="blue darken-1" text @click="deleteItemConfirm">确定</v-btn>
                                <v-spacer></v-spacer>
                            </v-card-actions>
                        </v-card>
                    </v-dialog>
                </v-card>
            </v-col>
        </v-row>
        <v-row>
            <v-col>
                <v-snackbar v-if="!failed" v-model="alert" :timeout="3000" color="success">
                    {{ info }}
                </v-snackbar>
                <v-snackbar v-else v-model="alert">
                    {{ info }}

                    <template v-slot:action="{ attrs }">
                        <v-btn color="red" text v-bind="attrs" @click="alert = false">
                            关闭
                        </v-btn>
                    </template>
                </v-snackbar>
            </v-col>
        </v-row>
    </v-container>
</template>
<script>
export default {
    data: () => ({
        headers: [
            {
                text: '用户',
                align: 'start',
                value: 'name',
                sortable: false,
            },
            {
                text: '时间',
                value: 'when',
                sortable: false,
            },
            {
                text: '',
                value: 'data-table-expand'
            },
            {
                text: '动作',
                value: 'actions',
                sortable: false
            },
        ],
        headersDetail: [
            {
                text: '工具类型',
                align: 'start',
                sortable: false,
                value: 'tool_type',
            },
            {
                text: '工具名称',
                align: 'start',
                sortable: false,
                value: 'tool',
            },
            {
                text: '标识码',
                align: 'start',
                sortable: false,
                value: 'identifier',
            },
            {
                text: '所属抽屉',
                align: 'start',
                sortable: false,
                value: 'drawer',
            },
            {
                text: '借出/归还',
                value: 'dispense',
            },
        ],
        logs: [
            {
                id: 1,
                name: '刘康',
                when: '2023-01-22 19:14'
            },
            {
                id: 2,
                name: 'Admin',
                when: '2023-01-21 08:00',
            },
        ],
        logDetails: [
            {
                id: 1,
                parentId: 1,
                tool: 2,
                dispense: true,
            },
            {
                id: 2,
                parentId: 1,
                tool: 3,
                dispense: false,
            },
            {
                id: 3,
                parentId: 1,
                tool: 4,
                dispense: false,
            },
            {
                id: 4,
                parentId: 2,
                tool: 2,
                dispense: false,
            },
            {
                id: 5,
                parentId: 2,
                tool: 3,
                dispense: true,
            },
            {
                id: 6,
                parentId: 2,
                tool: 4,
                dispense: true,
            },
        ],
        toolList: [
            {
                id: 1,
                type: 1,
                name: '尖嘴钳',
                drawer: 1,
                identifier: 'AA',
            },

            {
                id: 2,
                type: 2,
                name: '十字改锥',
                drawer: 1,
                identifier: 'BB',
            },
            {
                id: 3,
                type: 3,
                name: '14mm',
                drawer: 1,
                identifier: 'CC',
            },
            {
                id: 4,
                type: 1,
                name: '斜口钳',
                drawer: 2,
                identifier: 'DD',
            },
            {
                id: 5,
                type: 2,
                name: '一字改锥',
                drawer: 2,
                identifier: 'EE',
            },
            {
                id: 6,
                type: 3,
                name: '16mm',
                drawer: 2,
                identifier: 'FF',
            },
            {
                id: 7,
                type: 1,
                name: '管钳',
                drawer: 3,
                identifier: 'GG',
            },
            {
                id: 8,
                type: 2,
                name: '星型改锥',
                drawer: 3,
                identifier: 'HH',
            },
            {
                id: 9,
                type: 3,
                name: '梅花扳手',
                drawer: 3,
                identifier: 'II',
            },
        ],
        toolTypes: [
            {
                id: 1,
                name: '钳子',
            },
            {
                id: 2,
                name: '改锥',
            },
            {
                id: 3,
                name: '扳手',
            },
        ],
        drawerList: [
            {
                id: 1,
                name: '抽屉一',
            },
            {
                id: 2,
                name: '抽屉二',
            },
            {
                id: 3,
                name: '抽屉三',
            }
        ],
        logCount: 0,
        loading: false,
        options: {},
        alert: false,
        info: '',
        failed: false,
        dialogDelete: false,
        id: -1,
        name: '',
        dates: [],
        modal: false,
    }),
    methods: {
        getLog() {
            const { page, itemsPerPage } = this.options
            this.logManage.getLog(page - 1, itemsPerPage, this.name, JSON.stringify(this.dates))
            this.loading = true
        },

        deleteItem(item) {
            this.id = item.id
            this.dialogDelete = true
        },
        deleteItemConfirm() {
            this.logManage.delLog(this.id).then(retVal => {
                if (retVal === true) {
                    this.info = '删除日志成功'
                    this.failed = false
                    this.alert = true

                    this.getLog()
                } else {
                    this.info = '删除日志失败'
                    this.failed = true
                    this.alert = true
                }
            })
            this.closeDelete()
        },

        closeDelete() {
            this.dialogDelete = false
            this.$nextTick(() => {
                this.id = -1
            })
        },

        onItemExpanded({ item, value }) {
            if (value == true) {
                this.logManage.getLogDetail(item.id)
                this.loading = true
            }
        },

        exportLog() {
            this.logManage.exportLog(this.name, JSON.stringify(this.dates))
            this.loading = true
        },

        onClearDate() {
            this.dates = []
        },

        onLogGot(succeed, resultOrErrInfo) {
            if (succeed) {
                let items = JSON.parse(resultOrErrInfo)
                const { sortBy, sortDesc } = this.options
                if (sortBy.length === 1 && sortDesc.length === 1) {
                    items = items.sort((a, b) => {
                        const sortA = a[sortBy[0]]
                        const sortB = b[sortBy[0]]

                        if (sortDesc[0]) {
                            if (sortA < sortB) return 1
                            if (sortA > sortB) return -1
                            return 0
                        } else {
                            if (sortA < sortB) return -1
                            if (sortA > sortB) return 1
                            return 0
                        }
                    })
                }
                this.logs = items

                this.loading = false
            } else {
                this.loading = false

                this.info = '获取日志失败，原因：' + resultOrErrInfo
                this.failed = true
                this.alert = true
            }
        },
        onLogDetailGot(succeed, resultOrErrInfo) {
            if (succeed) {
                this.logDetails = JSON.parse(resultOrErrInfo)

                this.loading = false
            } else {
                this.loading = false

                this.info = '获取日志详情失败，原因：' + resultOrErrInfo
                this.failed = true
                this.alert = true
            }
        },

        onLogExported(succeed, errInfo) {
            if (succeed) {
                this.loading = false

                this.info = '导出日志成功'
                this.failed = false
                this.alert = true
            } else {
                this.loading = false

                this.info = '导出日志失败, 原因：' + errInfo
                this.failed = true
                this.alert = true
            }
        }
    },
    computed: {
        date() {
            return this.dates.join(' ~ ')
        },
    },
    watch: {
        options: {
            handler() {
                if (this.logManage != null) {
                    this.getLog()
                }
            },
            deep: true,
        },
    },
    mounted: async function () {
        this.logManage.logGot.connect(this.onLogGot)
        this.logManage.logDetailGot.connect(this.onLogDetailGot)
        this.logManage.logExported.connect(this.onLogExported)

        this.toolTypes = JSON.parse(await this.toolManage.getToolTypes())
        this.drawerList = JSON.parse(await this.toolManage.getDrawerList())
        this.toolList = JSON.parse(await this.toolManage.getToolList())
        this.logCount = await this.logManage.getLogCount()
    },
    unmounted: function () {
        this.logManage.logGot.disconnect(this.onLogGot)
        this.logManage.logDetailGot.disconnect(this.onLogDetailGot)
        this.logManage.logExported.disconnect(this.onLogExported)
    },
}
</script>